package com.example.dazuoye.controller;

import com.example.dazuoye.mapper.SearchCarRepository;
import com.example.dazuoye.model.Car;
import com.example.dazuoye.model.Order;
import com.example.dazuoye.model.SearchCar;
import com.example.dazuoye.model.User;
import com.example.dazuoye.service.UserService;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class Usercontroller {
    /*@PostMapping(value = "/login")
      @ResponseBody
      public String login(HttpServletRequest request,
                          HttpServletResponse response,
                          @RequestBody User u) {
          response.setHeader("Access-Control-Allow-Origin","*");;
          JSONObject j = JSONObject.fromObject(u);


      }*/
    @Autowired(required = true)
    private UserService serv;
    @Autowired
    private SearchCarRepository searchCarRepository;
    private static final Logger logger =  LoggerFactory.getLogger(Usercontroller.class);
    @ResponseBody
    public static String GET(String url) {
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "/login")
    public String getOpenid(@RequestParam(value = "code") String getcode) {
        String code = getcode;
        //得到front中的res.code
        //还没改这个ID 和密钥  我另外放一个文件
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        //使用replace代替就完事了嗷
        String requesetUrl = WX_URL.replace("APPID", "wx89c4ef60bc5f7dff").replace("SECRET", "cb0b85a2df178a8fec2d038e8989e06a").replace("JSCODE", code).replace("authorization_code", "authorization_code");
        //get请求
        String returnvalue = GET(requesetUrl);
        System.out.println(returnvalue);
        JSONObject convertvalue = JSONObject.fromObject(returnvalue);
        System.out.println("return openid is" + convertvalue.get("openid"));
        System.out.println("return sessionkey is ：" + convertvalue.get("session_key"));
        String openid = (String) convertvalue.get("openid");
        String sessionkey = (String) convertvalue.get("session_key");
        System.out.println(getcode);
        User t1=serv.getuserinfo(openid);
        if (t1==null) serv.insertuser(openid,0,0,0,0);
        return openid;
    }
    @ResponseBody
    @RequestMapping(value="/costmoney") //强制扣钱接口
    public JSONObject costmoney(@RequestParam(value="u_id") String userid,@RequestParam(value="amount") int amount)
    {
        serv.costmoney(userid,amount);
        return JSONObject.fromObject(serv.getwalletinfo(userid));
    }
    @ResponseBody
    @RequestMapping(value = "/newuser")
    public String newuser(@RequestParam(value = "u_id") String userid) {
        serv.insertuser(userid,0,0,0,0);
        return "用户创建成功";
    }
    @ResponseBody
    @RequestMapping(value="/userinfo")
    public JSONObject ui(@RequestParam(value="u_id") String u_id)
    {
        //System.out.println(serv.getuserinfo(u_id));
        return JSONObject.fromObject(serv.getuserinfo(u_id));
    }
    @ResponseBody
    @RequestMapping(value = "/carinfo")
    public JSONObject getcarinfo(@RequestParam(value = "c_id") int c_id) {
        return JSONObject.fromObject(serv.getcarinfo(c_id));
    }


    @ResponseBody
    @RequestMapping(value = "/getallcar")
    public JSONArray getallcar() {
        return JSONArray.fromObject(serv.getallcar());
    }
    @ResponseBody
    @RequestMapping(value="/getunusedcar")
    public JSONArray getunusedcar()
    {
        return JSONArray.fromObject(serv.getunusedcar());
    }
   @ResponseBody
   @RequestMapping(value = "/search")
   public Page<SearchCar> searchbytitle(@RequestParam("searchkey")String searchkey){
        logger.info(searchkey);
       NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
       queryBuilder.withQuery(QueryBuilders.matchQuery("title",searchkey));
       Page<SearchCar> searchCars = this.searchCarRepository.search(queryBuilder.build());
       logger.info(searchCars.toString());
       return searchCars;
   }
    @ResponseBody
    @RequestMapping(value = "/getmoney")
    public int getmoney(@RequestParam(value = "u_id") String u_id) {
        System.out.println(u_id);
        return serv.getwalletinfo(u_id).getMoney();
    }
    @ResponseBody
    @RequestMapping(value = "/getvip")
    public String getvip(@RequestParam(value = "u_id") String u_id) {
        Date p=serv.getvipinfo(u_id);
        if (p==null) return "";
        //System.out.println(p);
        SimpleDateFormat format0=new SimpleDateFormat("yyyy-MM-dd");
        return format0.format(p);
        //return String.valueOf(serv.getvipinfo(u_id));
    }
    @ResponseBody
    @RequestMapping(value = "/getdeposit")
    public String getdeposit(@RequestParam(value = "u_id") String u_id) {
        return String.valueOf(serv.getwalletinfo(u_id).getDeposit());
    }
    @ResponseBody
    @RequestMapping(value = "/getcoupon")
    public String getcoupon(@RequestParam(value = "u_id") String u_id) {
        return "您的优惠券数量为： "+String.valueOf(serv.getwalletinfo(u_id).getCoupon_count())+"张";
    }
    @ResponseBody
    @RequestMapping(value = "/getacceptstate")
    public String getacceptstate(@RequestParam(value = "u_id") String u_id) {
        String text;
        if (serv.getuserinfo(u_id).getUploaded()==0) return "未提交";
        int i=serv.getuserinfo(u_id).getAccepted();
        if(i==1)
            text = "已审核";//1 已经accept 0 未accept
        else
            text="未审核";
        return text;
    }
    @ResponseBody
    @RequestMapping(value = "/checkusingstate")
    public String check(@RequestParam(value = "c_id") int c_id) {
        return String.valueOf(serv.getusingstate(c_id)); //1 已经被占用 0 可用
    }
    @ResponseBody
    @RequestMapping(value = "/borrow")
    public String borrow(@RequestParam(value = "c_id") int c_id) { //1 借车成功 0 失败，车被占用
        int tmp=serv.getusingstate(c_id);
        if (tmp==1) return String.valueOf(0);
        serv.setusingstate(c_id,1);
        return String.valueOf(1);
    }
    @ResponseBody
    @RequestMapping(value="/return")
    public String returncar(@RequestParam(value="c_id") int c_id) { //1 还车成功 0 还车失败，没被借
        int tmp=serv.getusingstate(c_id);
        if (tmp==0) return String.valueOf(0);
        serv.setusingstate(c_id,0);
        return String.valueOf(1);
    }
    @ResponseStatus(code= HttpStatus.BAD_REQUEST,reason="nomoney")
    public class ServerException extends Exception {
    }
    @ResponseBody
    @RequestMapping(value = "/newvip")
    public String newvip(@RequestParam(value = "u_id") String u_id,@RequestParam("amount") int amount) throws ServerException
    {
        if (serv.getwalletinfo(u_id).getMoney()<30) throw new ServerException();
        Date tmp=new Date();
        Calendar now=Calendar.getInstance();
        now.setTime(tmp);
        now.add(Calendar.MONTH,amount);
        Date t2=now.getTime();
        //System.out.println(t2);
        serv.setviptime(u_id,t2);
        costmoney(u_id,30);
        return "充值vip成功";
    }
    @ResponseBody
    @RequestMapping(value = "/plusvip")
    public String plusvip(@RequestParam(value = "u_id") String u_id,@RequestParam("amount") int amount) throws ServerException
    {
        if (serv.getwalletinfo(u_id).getMoney()<30) throw new ServerException();
        Date tmp=serv.getvipinfo(u_id);
        Calendar now=Calendar.getInstance();
        now.setTime(tmp);
        now.add(Calendar.MONTH,amount);
        Date t2=now.getTime();
        //System.out.println(t2);
        serv.setviptime(u_id,t2);
        costmoney(u_id,30);
        return "续费vip成功";
    }
    @ResponseBody
    @RequestMapping(value = "/getaccepted")
    public String getaccepted(@RequestParam(value = "u_id") String u_id) { //1 通过验证 0未通过验证
        return getacceptstate(u_id);
    }
    @ResponseBody
    @RequestMapping(value="/charge")
    public JSONObject charge(@RequestParam(value="u_id") String u_id,@RequestParam(value="amount") int amount){
        serv.charge(u_id,amount);
        return JSONObject.fromObject(serv.getwalletinfo(u_id));
    }
    @ResponseBody
    @RequestMapping(value="/paydeposit")
    public String pd(@RequestParam(value="u_id") String u_id,@RequestParam(value="amount") int amount) throws ServerException{
        int dp=serv.getwalletinfo(u_id).getDeposit();
        if (dp!=0) throw new ServerException();
        dp=serv.getwalletinfo(u_id).getMoney();
        //System.out.println(dp);
        //System.out.println(amount);
        if (dp<amount) throw new ServerException();
        serv.pd(u_id,amount);
        serv.costmoney(u_id,amount);
        return "押金缴纳成功";
    }
    @ResponseBody
    @RequestMapping(value="/returndeposit")
    public String rd(@RequestParam(value="u_id") String u_id)
    {
        int dp=serv.getwalletinfo(u_id).getDeposit();
        System.out.println(dp);
        if (dp==0) return "押金未缴纳";
        serv.pd(u_id,-dp);
        serv.costmoney(u_id,-dp);
        return "退押金成功";
    }
    @ResponseBody
    @RequestMapping(value="/getcarsite")
    public String gcs(@RequestParam(value="c_id") int c_id)
    {
        return serv.getcarsite(c_id);
    }
    @ResponseBody
    @RequestMapping(value="/setcarsite")
    public String scs(@RequestParam(value = "c_id") int c_id,@RequestParam(value="carsite") String carsite)
    {
        serv.setcarsite(c_id,carsite);
        return serv.getcarsite(c_id);
    }
    @ResponseBody
    @RequestMapping(value = "/insertthefirsttime")
    public void itf(@RequestParam(value = "u_id")String u_id,@RequestParam("c_id") int c_id)
    {
         Date date = new Date();
         serv.starttime(u_id,c_id,date);
    }
    @ResponseBody
    @RequestMapping(value = "/displayforthecar")
    public  String pft(@RequestParam(value = "u_id")String u_id,@RequestParam("c_id") int c_id)
    {Date p=serv.getvipinfo(u_id);
           System.out.println(u_id);
           System.out.println(c_id);
           Date today = new Date();
           Date priday = serv.searchstarttime(u_id,c_id);
           System.out.println(priday);
          Long totime = today.getTime();
          Long pritime = priday.getTime();
          Long time = totime-pritime;
          Long sec=time/1000;
           Long minutes = sec/60;
           String payoff;
        if(0<=minutes&&minutes<=3&& p ==null)
            payoff = "12";
        else if(0<=minutes&&minutes<=3&& p !=null)
            payoff = "10";
        else if(p==null&&minutes>3)
            payoff = String.valueOf(12+((new Long(minutes).intValue())-3)*3);
        else
            payoff = String.valueOf(10+((new Long(minutes).intValue())-3)*2);
           serv.finish(u_id,c_id,today,payoff);
           return payoff;
    }
    @ResponseBody
    @RequestMapping("/payforthecar")
    public String payf(@RequestParam(value = "u_id")String u_id,@RequestParam("amount")String money)
    {
        serv.costmoney(u_id,Integer.valueOf(money));
        return "ass we can";
    }
    @ResponseBody
    @RequestMapping("/getorder")
    public JSONArray getorder(@RequestParam(value="u_id") String u_id)
    {
        List<HashMap<String,String>> rv=new ArrayList<>();
        SimpleDateFormat bjt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bjt.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        for (Order x:serv.getorder(u_id))
        {
            HashMap<String,String> tmpx=new HashMap<>();
            tmpx.put("u_id",x.getU_id());
            tmpx.put("c_id",String.valueOf(x.getC_id()));
            tmpx.put("start",bjt.format(x.getStart()));
            Date td=x.getFinish();
            if (td==null)
            {
                tmpx.put("finish","未还车");
                tmpx.put("payoff","未计算");
            }else
            {
                tmpx.put("finish",bjt.format(td));
                tmpx.put("payoff",x.getPayoff());
            }
            tmpx.put("dingdanid",String.valueOf(x.getDingdanid()));
            tmpx.put("tips",x.getTips());
            rv.add(tmpx);
        }
        return JSONArray.fromObject(rv);
    }
    @ResponseBody
    @RequestMapping("/getfinishorder")
    public JSONArray getfinishorder(@RequestParam(value="u_id") String u_id)
    {
        List<HashMap<String,String>> rv=new ArrayList<>();
        SimpleDateFormat bjt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bjt.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        for (Order x:serv.getfinishorder(u_id))
        {
            HashMap<String,String> tmpx=new HashMap<>();
            tmpx.put("u_id",x.getU_id());
            tmpx.put("c_id",String.valueOf(x.getC_id()));
            tmpx.put("start",bjt.format(x.getStart()));
            Date td=x.getFinish();
            if (td==null)
            {
                tmpx.put("finish","未还车");
                tmpx.put("payoff","未计算");
            }else
            {
                tmpx.put("finish",bjt.format(td));
                tmpx.put("payoff",x.getPayoff());
            }
            tmpx.put("dingdanid",String.valueOf(x.getDingdanid()));
            tmpx.put("tips",x.getTips());
            rv.add(tmpx);
        }
        return JSONArray.fromObject(rv);
    }
    @ResponseBody
    @RequestMapping("/getunfinishorder")
    public JSONArray getunfinishorder(@RequestParam(value="u_id") String u_id)
    {
        List<HashMap<String,String>> rv=new ArrayList<>();
        SimpleDateFormat bjt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bjt.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        for (Order x:serv.getunfinishorder(u_id))
        {
            HashMap<String,String> tmpx=new HashMap<>();
            tmpx.put("u_id",x.getU_id());
            tmpx.put("c_id",String.valueOf(x.getC_id()));
            tmpx.put("start",bjt.format(x.getStart()));
            Date td=x.getFinish();
            if (td==null)
            {
                tmpx.put("finish","未还车");
                tmpx.put("payoff","未计算");
            }else
            {
                tmpx.put("finish",bjt.format(td));
                tmpx.put("payoff",x.getPayoff());
            }
            tmpx.put("dingdanid",String.valueOf(x.getDingdanid()));
            tmpx.put("tips",x.getTips());
            rv.add(tmpx);
        }
        return JSONArray.fromObject(rv);
    }
}
